package com.justnow;

import java.util.Scanner;

/**
 * @author justnow
 * Created on 2020-09-27
 * Description
 *
 * 输入：
 * 1
 * 7 3
 * 0 2
 * 2 0
 * 4 4
 *
 * 输出
 * 1
 * 7 3
 * 0 2
 * 2 0
 * 4 4
 */
public class Wy01 {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        int T = scanner.nextInt();
        for (int i = 0; i < T; i++) {
            int N = scanner.nextInt();
            int[][] array = getArray(N);
            int m = scanner.nextInt();
            for (int j = 0; j < m; j++) {
                int x = scanner.nextInt();
                int y = scanner.nextInt();
                System.out.println(array[x][y]);
            }
        }
    }

    public static int[][] getArray(int N) {
        int[][] array = new int[N][N];
        int left = 0, right = N - 1, top = 0, bottom = N - 1;
        int index = 1, last = N * N;
        int level = N / 2;
        while (index <= last) {
            for (int k = 0; k < level; k++) {
                if (k % 2 == 0) {
                    for (int i = left; i <= right; i++) {
                        array[top][i] = index++;
                    }
                    top++;
                    for (int i = top; i <= bottom; i++) {
                        array[i][right] = index++;
                    }
                    right--;
                    for (int i = right; i >= left; i--) {
                        array[bottom][i] = index++;
                    }
                    bottom--;
                    for (int i = bottom; i >= top; i--) {
                        array[i][left] = index++;
                    }
                    left++;
                } else {
                    for (int i = top; i <= bottom ; i++) {
                        array[i][left] = index++;
                    }
                    left++;
                    for (int i = left; i <= right; i++) {
                        array[bottom][i] = index++;
                    }
                    bottom--;
                    for (int i = bottom; i >= top; i--) {
                        array[i][right] = index++;
                    }
                    right--;
                    for (int i = right; i >= left ; i--) {
                        array[top][i] = index++;
                    }
                    top++;
                }
            }
        }

        if (N % 2 != 0) {
            array[level][level] = N * N;
        }
        return array;
    }
}
